package cn.gson.querydsl.dao.impl;

import cn.gson.querydsl.dao.Query;
import cn.gson.querydsl.dao.QueryHandler;
import cn.gson.querydsl.dao.TupleResult;
import jakarta.persistence.Tuple;
import org.hibernate.SessionFactory;

import java.lang.reflect.Method;

/**
 * <p>****************************************************************************</p>
 * <ul style="margin:15px;">
 * <li>Description : ListQueryHandler</li>
 * <li>Version     : 1.0</li>
 * <li>Creation    : 2024年07月19日</li>
 * <li>@author     : ____′↘夏悸</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class ListQueryHandler implements QueryHandler {
    private final SessionFactory sessionFactory;
    private final Class<?> returnType;
    private final Query query;

    public ListQueryHandler(SessionFactory sessionFactory, Class<?> returnType, Query query, boolean isNative) {
        this.sessionFactory = sessionFactory;
        this.returnType = returnType;
        this.query = query;
    }

    @Override
    public Object doQuery(Method method, Object[] args) throws Throwable {
        return getQuery(query, args, Tuple.class).setTupleTransformer(new TupleResult(returnType)).list();
    }

    private org.hibernate.query.Query getQuery(Query query, Object[] args, Class<?> returnType) {
        org.hibernate.query.Query exeQuery = sessionFactory.openSession().createQuery(query.value(), returnType);
        if (args != null)
            for (int i = 0; i < args.length; i++)
                exeQuery.setParameter(i + 1, args[i]);
        return exeQuery;
    }
}
